package com.excel.poi.demo;

import com.alibaba.fastjson.JSON;
import com.excel.poi.excel.ExcelWriter;
import com.excel.poi.function.ImportFunction;
import com.excel.poi.utils.Converters;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Miaoxiong Fan
 * @description 测试导入导出
 * @data 2019/1/31
 */
@RestController
@RequestMapping("/demo")
public class DemoController {

    @PostMapping("/import")
    public void hello(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
        List<TestQuestionImport> errorList = new ArrayList<>();
        int beginReadRowIndex = 2;
        com.kingdee.shr.ques.cloud.poi.ExcelBoot.ImportBuilder(file.getInputStream(),  TestQuestionImport.class)
                .importExcel(new ImportFunction<TestQuestionImport>() {
                    @Override
                    public void onProcess(int sheetIndex, int rowIndex, TestQuestionImport poi) {
                        System.out.println("sheetIndex = [" + sheetIndex + "], rowIndex = [" + rowIndex + "], poi = [" + JSON.toJSONString(poi) + "]");
                        return;
                    }

                    @Override
                    public void onError(List<String> errorEntity , TestQuestionImport error) {
                        error.setDesc(StringUtils.join(errorEntity , ","));
                        errorList.add(error);
                        System.out.println("errorEntity = [" + JSON.toJSONString(errorEntity) + "]");
                    }
                } , beginReadRowIndex);
        if(errorList.size() > 0) {
            List<String> descList = ExcelWriter.getCommonDescList();
            descList.add("当题型为选择题时，选择项必录");
            try {
                com.kingdee.shr.ques.cloud.poi.ExcelBoot.ExportBuilder(response, "问卷题目导入错误日志", TestQuestionImport.class).exportTemplate(null , Converters.to(errorList) , beginReadRowIndex , descList);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 导出Excel模板
     */
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) throws InstantiationException, IllegalAccessException {
        List<String> descList = ExcelWriter.getCommonDescList();
        descList.add("当题型为选择题时，选择项必录");
        com.kingdee.shr.ques.cloud.poi.ExcelBoot.ExportBuilder(response, "问卷题目导入模板", TestQuestionTemplate.class).exportTemplate(null , null , 2 , descList);
    }
}
